// JavaScript Document

var downloads = {
	
	// stores a reference to the currently loaded article category for quick addition
	category_id: null,
	
	// stores a reference to the last selected category link
	lastCategoryLink: null,
	
	// parent ID of currently editted category
	lastCategoryParentID: null,
	
	// ajax page
	ajax_page : null,

	init: function() {
		
		// initialise the Pane UI JS Library
		paneUI.init({
			contentName: 'Downloads',
			ajax_page: 'ajax_pages/downloads.php',
			
            onEditorLoaded: function() {
                downloads.bindListeners();
            }
		});

	},
	
	bindListeners: function() {

        // make the add or save button process the form
        if( paneUI.editorState == 'add' ) {
            $p("#dwn-save-btn").val("Add Download").bind('click',function() {
                downloads.saveDownload();
            });
        } else {
            $p("#dwn-save-btn").val("Save Changes").bind('click',function() {
                downloads.updateDownload();
            });
        }

        // make the cancel button hide the paneUI editor
        $p("#dwn-cancel-btn").bind("click", function() {
            paneUI.hideItemEditor();
        });

        // make the Description field an HTML editor
		ui.htmlMiniEditor("Description");
		
		// attach a change event handler to the Category field
		$p('#Category').bind('change', function() {
			var value = this.value;
			document.getElementById("uploadFile").disabled = value == '';	
		});
		
		// attach a handler to the uploadFile field if it exists
        $p('#uploadFile').bind('change', function() {
            
			var category = document.getElementById("Category").value;
            var dstFolder = "../assets/downloads/" + category + "/";
            var file_path = document.getElementById("uploadFile").value;
			
			// calculate the data time to be used as the destination file name
			var now = new Date();
            var dateStr = now.getFullYear() + "" + (now.getMonth() + 1) + "" + now.getDate() + "_" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
			document.getElementById('destFileName').value = "file" + dateStr;
			document.getElementById("destFolder").value = dstFolder;
			
			// generate the destination file name to used for the picture field
            file_utils.generateDestinationFileName('url', dstFolder, file_path, 'file');
			
			//alert( dstFolder + "\n" + document.getElementById('url').value );
        });
		
		$("#downloads_form #Name").friendurl({id:'Alias'});	
		//$("#ArticleTitle").friendurl({id:'ArticleTitleAlias'});
	},

    saveDownload: function() {
        
        // save the field contents so we can validate the fields
        tinyMCE.triggerSave();

        var valid = $p("#downloads_form").validate({
            'Category': 'Please Select A Category For The Download',
            'Name': 'Please Provide A Name For This Download',
            'Alias': 'Please Provide A Valid Alias For The Download Name',
            'Description': 'Please Provide A Valid Description For The Download',
            'uploadFile': 'Select The File To Be Uploaded'
        });

        if( !valid ) {
            return;
        }
        
        var form = document.getElementById("downloads_form");

        pageManager.postMultiPartForm( paneUI.ajax_page, form, null, function(data) {
            
            if( data ) {
                pageManager.showMessage({
                   title: 'File Save Error',
                   content: data,
                   width: '320px'
                });
            }

            paneUI.hideItemEditor();

            try {
                tinyMCE.remove( tinyMCE.getInstanceById('Description') );
            } catch(e) {}

            // reload the current category of articles
            var selected_cat_id = $p("#downloads_form #Category").val();
            var link = paneUI.getCategoryLink(selected_cat_id);
            paneUI.loadItems( link );
        });
    },

    updateDownload: function() {
		tinyMCE.triggerSave();

        var valid = $p("#downloads_form").validate({
            'Category': 'Please Select A Category For The Download',
            'Name': 'Please Provide A Name For This Download',
            'Alias': 'Please Provide A Valid Alias For The Download Name',
            'Description': 'Please Provide A Valid Description For The Download'
        });

        if( !valid ) {
            return;
        }

        var query = $p("#downloads_form").serialize();
        
        pageManager.post( paneUI.ajax_page, query, null, function() {
            paneUI.hideItemEditor();

            try {
                tinyMCE.remove( tinyMCE.getInstanceById('Description') );
            } catch(e) {}
            
            paneUI.reloadItems();
        });
    }
};